<template>
	<view>

		<view class="cart" @click="showClick">
			<view class="cart-button">
				<l-ball ref="ballRef" class="u-p-l-14">
					<template #default="{active}">
						<view class="cart-icon">
							<image class="img" :class="{active}" mode="widthFix"
								src="/static/images/shop/shop-cart.png">
							</image>
							<text class="badge">{{orderPinia.shopList.length}}</text>
						</view>
					</template>
				</l-ball>
			</view>
			<view class="cart-prices">
				<view class="price">
					<view class="payableAmount">
						<text class="text">￥</text>
						<text class="text number">{{orderPinia.price}}</text>
					</view>
					<view class="totalAmount">
						<text class="text line-del">¥{{orderPinia.salePriceToal}}</text>
					</view>
				</view>
			</view>
			<view class="cart-preview" @click.stop="orderPinia.toSettle()">去结算</view>
		</view>

		<u-popup v-model="props.modelValue" zIndex="999" mode="bottom" borderRadius="18" @close="shopCarClose">
			<view class="Model">
				<view class="title u-rela"><text>购物车</text>
					<view class="poi u-flex">
						<u-icon @click="orderPinia.shopDelAll" size="28" name="trash-fill" class="color-gary-xs"
							label="清空购物车"></u-icon>
					</view>
				</view>


				<view class="u-p-t-30" v-if="orderPinia.shopList.length===0">
					<u-empty text="未添加商品"></u-empty>
				</view>

				<scroll-view class="main" :scroll-y='true'>
					<view class="u-flex u-p-24" v-for="(item,index) in orderPinia.shopList" :key="index">
						<u-image width="100" height="100" :src="item.mainImage"></u-image>
						<view class="u-flex-1 u-m-l-16">
							<view>{{item.name}}</view>
							<view v-if="item.goodsType == 1 && item.variantState == 2">
								{{item.sku}}

							</view>
				<!-- 			<view v-if="item.goodsType == 2 && item.variantState == 1">
								{{item.sku}}
							
							</view> -->
							<view class="color-red u-font-xs">￥<text class="u-font-lg">{{item.price}}</text> <text
									class="line-del color-gary-xs u-m-l-10">{{item.salePrice}}</text></view>
						</view>
						<!-- <u-number-box @change="orderPinia.setShop(item)" :index="index" v-model="item.nums" disabled-input></u-number-box> -->
						<view class="u-flex">
							<u-button :disabled="item.nums==0" @click="inputChange('-',item,'l',index)" size="mini">-</u-button>
							<input type="text" :value="item.nums" disabled class="inputstyl">
							<u-button @click="inputChange('+',item,'l')" size="mini">+</u-button>
						</view>
					</view>
					<view class="footer"></view>
				</scroll-view>

			</view>

		</u-popup>

		<u-popup v-model="seleShow" mode="bottom" border-radius="28">
			<view class="seleModel">
				<!--  商品信息 -->
				<view class="u-flex u-col-top">
					<u-image width="160" height="160" :src="goodsuse?.mainImage"></u-image>
					<view class="u-m-l-14 u-flex-1">
						<view class="u-font-xl fw-large">{{goodsuse?.name}}</view>
						<view class="u-font-md color-gary-xs u-m-t-12">{{goodsuse?.introduce}}</view>
					</view>
				</view>

				<!-- 商品参数 -->
				<scroll-view scroll-y style="max-height: 45vh;" class="u-m-t-32">

					<block v-for="(item,index) in goodsComboList" :key="index">
						<view class="u-font-lg fw-middel">{{item.comboName}} ({{item.list.length}}选{{item.chooseNums}})
						</view>
						<view class=" btnGrid">

							<view @click="items.saleState==2?comBoSelect(items,item):''"
								:style="items.saleState==2?'':'opacity: .3'" :class="items.select?'active':''"
								v-for="(items,indexs) in item.list" :key="indexs">{{items.relationGoodsName}}</view>
						</view>
					</block>

					<block v-for="(item,index) in goodDetail?.specList" :key="index">
						<view class="u-font-lg fw-middel">{{item.specName}}</view>
						<view class=" btnGrid">
							<view :style="items.select?'opacity: .3':''"
								@click="items.select?'':selectDetail(index,items.specVal,items)"
								:class="goodDetail.defaultVariant?.sku.split(':')[index] == items.specVal?'active':''"
								v-for="(items,indexs) in item.specValList" :key="indexs">{{items.specVal}}</view>
						</view>
					</block>

					<block v-for="(item,key,index) in mapdetail" :key="index">
						<view class="u-font-lg fw-middel u-m-t-18">{{key}}</view>
						<view class=" btnGrid full">
							<view @click="valiClickFull(key,items)" :class="items.select?'active':''"
								v-for="(items,indexs) in item" :key="indexs">{{items.name}} {{items.salePrice}}元
							</view>
						</view>
					</block>
				</scroll-view>

				<!-- 商品价格 -->
				<view class="u-flex u-row-between u-m-t-22">
					<view class="color-red">
						<text class="u-font-sm">￥</text>
						<text class="u-font-40 fw-middel">{{tatol}}</text>
					</view>

					<view class="u-flex">
						<u-button :disabled="item?.nums==0" @click="inputChange('-',goodsuse)" size="mini">-</u-button>
						<input type="text" :value="goodsuse?.nums" disabled class="inputstyl">
						<u-button @click="inputChange('+',goodsuse)" size="mini">+</u-button>
					</view>
				</view>

				<!-- 加入购物车 & 立即购买 -->
				<view class="btnWrap">
					<view class="" @click="addCartFun">加入购物车</view>
					<view class="" @click="toToalter">立即购买</view>
				</view>

				<view></view>

			</view>
		</u-popup>

	</view>
</template>

<script setup lang="ts">
	import { computed, reactive, ref, watch } from 'vue'
	import goodsApi from '@/api/goods'
	import orderSotre from '@/store/order'
	import goods from '@/api/goods';
	const orderPinia = orderSotre()

	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		}
	})

	const strSpecValId = ref('')

	const seleShow = ref(false)
	const goodDetail = reactive({
		defaultVariant: {},
		goods: {},
		specList: {},
		variantMap: {}
	})
	const mapdetail = ref({})
	const itemObj = ref({})

	const goodsComboList = ref([])
	const goodsuse = ref(undefined)


	const reset = () => {
		goodDetail.defaultVariant = {}
		goodDetail.goods = {}
		goodDetail.specList = {}
		goodDetail.variantMap = {}
		mapdetail.value = {}
		goodsComboList.value = []
		goodsuse.value = {}
		itemObj.value = {}
	}

	const istrue = computed(() => {
		let istrue = false
		Object.keys(goodDetail).find(item => {
			if (Object.keys(goodDetail[item]).length != 0) {
				istrue = true
			}
		})
		return istrue
	})


	const inputChange = (type, item,l,index) => {
		if(l!='l' && type=='-'){
			if(item.nums==1){
				return
			}
		}
		switch (type) {
			case '-':
				item.nums--
				break;
			case '+':
				item.nums++
				break;
		}
		
		if(l == 'l' && type=='-' && item.nums==0){
		orderPinia.minus(index)
		}
	}

	const minus = (e) => {
		if (e.value == 0) {
			orderPinia.minus(e.index)
		}
	}

	const comBoSelect = (item, wrap) => {

		item.select = !item.select
	}

	const addCartFun = () => {
		if (itemObj.value.goodsType == 2) {
			let istru = false
			let relationVariantIds = []
			goodsComboList.value.map(item => {
				let lis = item.list.filter(items => items.select)
				if (lis.length != item.chooseNums) {
					istru = true
				}
				relationVariantIds = relationVariantIds.concat(lis)
			})
			if (istru) {
				return uni.showToast({
					title: '请按规则选择套餐',
					icon: 'none'
				})
			}

			let obj = JSON.parse(JSON.stringify(goodsuse.value))
			let ids = relationVariantIds.map(item => item.relationVariantId)

			orderPinia.setShop(Object.assign(obj, { relationVariantIds: ids }))
		}
		if (itemObj.value.variantState == 2) {
			//goodDetail { variantMap defaultVariant specList goods}
			const variantMapArr = Object.entries(goodDetail.variantMap).map(([key, value]) => ({ [key]: value }));
			
			variantMapArr.forEach(obj => {
			  // 检查当前对象是否有指定的 key（即 '200:30'）
			  if (obj[goodDetail.defaultVariant.sku]) {
			    // 如果找到了对应的 key，获取其 goodsId
			    goodDetail.defaultVariant.variantId = obj[goodDetail.defaultVariant.sku].variantId;
			    // 停止遍历，因为已经找到了
			    return;
			  }
			});
			
			orderPinia.setShop(Object.assign(goodsuse.value, goodDetail.defaultVariant))
		}
		Object.keys(mapdetail.value).map(item => {
			mapdetail.value[item].map(items => {
				if (items.select) {
					items.nums = 1
					orderPinia.setShop(items)
				}
			})
		})
		seleShow.value = false
	}



	const toToalter = () => {//立即购买
		let talList = []
		if (itemObj.value.goodsType == 2) {
			let istru = false
			let relationVariantIds = []
			goodsComboList.value.map(item => {
				let lis = item.list.filter(items => items.select)
				if (lis.length != item.chooseNums) {
					istru = true
				}
				relationVariantIds = relationVariantIds.concat(lis)
			})
			if (istru) {
				return uni.showToast({
					title: '请按规则选择套餐',
					icon: 'none'
				})
			}

			let obj = JSON.parse(JSON.stringify(goodsuse.value))
			let ids = relationVariantIds.map(item => item.relationVariantId)

			talList.push(Object.assign(obj, { relationVariantIds: ids }))
		}
		if (itemObj.value.variantState == 2) {
			const variantMapArr = Object.entries(goodDetail.variantMap).map(([key, value]) => ({ [key]: value }));
			
			variantMapArr.forEach(obj => {
			  // 检查当前对象是否有指定的 key（即 '200:30'）
			  if (obj[goodDetail.defaultVariant.sku]) {
			    // 如果找到了对应的 key，获取其 goodsId
			    goodDetail.defaultVariant.variantId = obj[goodDetail.defaultVariant.sku].variantId;
			    // 停止遍历，因为已经找到了
			    return;
			  }
			});
			
			talList.push(Object.assign(goodsuse.value, goodDetail.defaultVariant))
		}

		Object.keys(mapdetail.value).map(item => {
			mapdetail.value[item].map(items => {
				if (items.select) {
					items.nums = 1
					talList.push(items)
				}
			})
		})
		uni.navigateTo({
			url: '/subpackage/order/goods/payment?list=' + encodeURIComponent(JSON.stringify(talList))
		})
	}

	const selectDetail = (index, id, items) => {
		let list = goodDetail.defaultVariant.sku.split(':')
		list[index] = id
		goodDetail.defaultVariant.sku = list.join(':')
	}

	const valiClick = (items) => {
		console.log(goodDetail.defaultVariant.sku);
		console.log(goodDetail.specList);
	}
	const valiClickFull = (key, item) => {
		mapdetail.value[key].map(w => {
			w.select = false
		})
		item.select = true

	}

	const celectOpen = async (item) => {
		uni.showLoading({
			title: '加载中',
		})
		reset()
		itemObj.value = item
		let goods = await goodsApi.goods({ id: item.goodsId })
		goods.data.nums = 1
		goodsuse.value = goods.data // 拿到该商品的所有信息 包含规格

		if (item.goodsType == 2) {
			let resCombo = await goodsApi.getGoodsCombo({ goodsId: item.goodsId })
			resCombo.data.map(item => {
				const chooseNums = item.chooseNums
				if (chooseNums == 1) {
					const target = item.list.find(item2 => item2.stock)
					if (target) {
						target.selected = true
					} else {

					}
				} else {

				}
			})
			goodsComboList.value = resCombo.data
		}

		if (item.variantState == 2) {
			//获取到当前商品的默认规格sku和variantId
			let res0 = await goodsApi.getSpecByGoodsId({ goodsId: item.goodsId })
			res0.data.goods.nums = 1
			strSpecValId.value = res0.data.defaultVariant.sku //defaultVariant.strSpecVal
			Object.assign(goodDetail, res0.data)
			//
		}

		if (item.relationFlag != 0) {
			let res1 = await goodsApi.getMap({
				beeperId: orderPinia.orderDetail.beeperId,
				goodsId: item.goodsId,
				thirdClassifyId: item.thirdClassifyId
			})
			Object.assign(mapdetail.value, res1.data)
		}




		seleShow.value = true

		uni.hideLoading()
		// Promise.all([
		// 	goodsApi.getSpecByGoodsId({ goodsId: item.goodsId }),
		// 	goodsApi.getMap({
		// 		beeperId: orderPinia.orderDetail.beeperId,
		// 		goodsId: item.goodsId,
		// 		thirdClassifyId: item.thirdClassifyId
		// 	})
		// ]).then(res => {
		// 	res[0].data.goods.nums = 1
		// 	strSpecValId.value = res[0].data.defaultVariant.strSpecVal
		// 	Object.assign(goodDetail, res[0].data)
		// 	Object.assign(mapdetail, res[1].data)

		// 	seleShow.value = true
		// }).finally(() => {
		// 	uni.hideLoading()
		// })

	}

	const mapItem = computed(() => {
		return goodDetail.defaultVariant
	})


	const emits = defineEmits(['update:modelValue','shopCarClose'])


	const showClick = () => {
		emits('update:modelValue', !props.modelValue)
	}

	watch(() => goodDetail.defaultVariant, (newVal) => {
		setDataFiliter()
		Object.keys(goodDetail.variantMap).find(item => {
			if (newVal === item) {

				Object.assign(goodDetail.defaultVariant, goodDetail.variantMap[item])
			}
		})
	})

	const tatol = computed(() => {

		let list = []
		Object.keys(mapdetail.value).map(item => {
			mapdetail.value[item].map(items => {
				if (items.select) {
					if (!items.nums) {
						items.nums = goodsuse.value.nums
					}
					list.push(items)
				}
			})
		})

		let price = list.reduce((res, items) => {

			return res += items.nums + items.salePrice
		}, 0)

		if (itemObj.value.variantState == 2) {
			price += (goodDetail.defaultVariant?.price * goodsuse.value.nums) + price
		}
		if (itemObj.value.goodsType == 2) {
			price += goodsuse.value.nums * goodsuse.value.salePrice
		}

		return price
	})


	// watch(() => goodDetail.defaultVariant, (newVal) => {
	// 	setDataFiliter()
	// })

	const setDataFiliter = () => {
		if (istrue.value) {
			let strSpecVal = goodDetail.defaultVariant?.sku?.split(':')
			// strSpecValId
			let keys = Object.keys(goodDetail.variantMap)
			let specList = goodDetail.specList
			let length = goodDetail.specList.length
			let arr = []
			for (let i = 0; i < length; i++) {
				let arr2 = keys.filter(item => {
					return strSpecVal.every((item2, index2) => {
						if (index2 == i) return true
						return item2 == item.split(":")[index2]
					})
				})
				if (arr2.length > 0) {
					arr2 = arr2.map(item => {
						return item.split(":")[i]
					})
				}
				arr[i] = Array.from(new Set(arr2))
			}

			specList.forEach((item, index) => {
				item.specValList.forEach(item2 => {
					// item2.specValId
					if (arr[index].some(item3 => item3 == item2.specVal)) {
						item2.select = false
					} else {
						item2.select = true
					}
				})
			})

			goodDetail.specList = specList
		}

	}
	const getGoodsCombo = (item) => {

	}
	
	const shopCarClose = () =>{
		emits('shopCarClose', false)
	}

	defineExpose({
		celectOpen
	})
</script>

<style lang="scss" scoped>
	.inputstyl {
		width: 50upx;
		text-align: center;
	}

	.img {
		width: 74upx;
		height: 122upx;
	}

	.seleModel {
		padding: 32upx 26upx 42upx;

		.btnGrid {
			margin: 24upx 0;
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			grid-gap: 22upx;

			>view {
				border-radius: 18upx;
				width: 100%;
				line-height: 65upx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				padding: 0 22upx;
				text-align: center;
				background-color: white;
				border: 1upx solid #c5c1c1;
			}

			>view.active {
				background-color: #ffc300;
				color: white;
				border-color: transparent;
			}

			>view.disabel {
				opacity: .3;
			}
		}

		.btnGrid.full {
			grid-template-columns: repeat(3, 1fr);
		}

		.btnWrap {
			display: flex;
			align-items: center;
			margin-top: 24upx;

			>view {
				height: 80upx;
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 600;
			}

			>view:first-child {
				background: linear-gradient(to right, #555555, #262729);
				color: #FEEEB2;
				border-top-left-radius: 45rpx;
				border-bottom-left-radius: 45rpx;
			}

			>view:last-child {
				background-color: #FFC300;
				border-top-right-radius: 45rpx;
				border-bottom-right-radius: 45rpx;
			}
		}

	}

	.Model {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.title {
			margin-bottom: 25upx;
			text-align: center;
			line-height: 80upx;
			background-color: #f8c74e;
			position: relative;

			text {
				font-size: 32upx;
			}

			.poi {
				position: absolute;
				right: 25upx;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.main {
			// padding-top: 20upx;
			box-sizing: border-box;
			max-height: 60vh;

			.footer {
				height: 240upx;
			}
		}
	}

	.list {
		padding: 30upx;

		.item {
			height: 100upx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			// text-align: right;
		}
	}

	.cart {
		z-index: 1000;
		position: fixed;
		left: 30upx;
		right: 30upx;
		bottom: 60upx;
		background: #222426;
		border-radius: 999upx;
		display: flex;
		align-items: center;
		color: #858687;
		// flex: 1;
		flex-direction: row;
		height: 100upx;


		.cart-icon {
			position: relative;
			margin: 0 20upx;
			// top: -20upx;

			.img {
				width: 94upx;
				transition: transform 0.3s ease;

				&.active {
					transform: scale(1.5);
				}
			}

			.badge {
				position: absolute;
				top: 23upx;
				right: -0upx;
				color: #fff;
				background-color: #FB4E44;
				font-size: 24upx;
				line-height: 36upx;

				text-align: center;
				transform: translate(50%, -50%);
				border-radius: 50%;
				width: 40upx;
				height: 40upx;
				box-sizing: border-box;
				padding: 2upx;
			}
		}

		.cart-prices {
			flex: 1;
			font-size: 28upx;
			flex-direction: row;

			.price {
				display: flex;
				align-items: center;
				flex-direction: row;
			}

			.text {
				color: #858687;
			}

			.payableAmount {
				// color: #fff;
				flex-direction: row;
				padding: 0 20upx 0 0;

				.text {
					color: #fff;
				}
			}

			.number {
				font-size: 40upx;
			}
		}

		.cart-preview {
			font-weight: 500;
			font-size: 28upx;
			color: #222426;
			height: 100upx;
			line-height: 100upx;
			background: #f8c74e;
			// background-image: linear-gradient(135deg, #FFDD33 0%, #FFBB33 100%);
			border-radius: 0 50upx 50upx 0;
			width: 150upx;
			position: relative;
			display: flex;
			justify-content: center;
		}
	}

	.cart2 {
		bottom: 50upx;
		justify-content: flex-end;
	}
</style>